/**
 *
 */
var dishesDY = [];
var Config = {
    createUrl: '/api/dinner/orders',
    updateUrl: '/api/dinner/orders',
    deleteUrl: '/api/dinner/orders',
    selectUrl: '/api/dinner/orders'
};
$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});

$(document).ready(function () {

    $.jgrid.defaults.styleUI = "Bootstrap";

    function loadGrid() {
        $("#data_list").jqGrid({
            datatype: "json",
            url: Config.selectUrl,
            height: 450,
            autowidth: true,
            shrinkToFit: true,
            rowNum: 12,
            colNames: ["编号", "订单号", "座号", "人数", "点菜", "应支付(元)", "是否支付", "备注", "发票抬头", "创建时间", "操作"],
            colModel: [{
                name: "id",
                index: "id",
                editable: false,
                width: 50,
                sorttype: "int",
                search: false
            }, {
                name: "orderNo",
                index: "orderNo",
                editable: false,
                width: 130,
                search: false
            }, {
                name: "tableNo",
                index: "tableNo",
                editable: false,
                width: 60
            }, {
                name: "cusNum",
                index: "cusNum",
                editable: false,
                width: 60
            }, {
                name: "orderDishes",
                index: "orderDishes",
                formatter: operateFmatterForDishes,
                width: 200,
                sortable: false
            }, {
                name: "realPay",
                index: "realPay",
                editable: false,
                width: 80
            }, {
                name: "payDesc",
                index: "payDesc",
                editable: false,
                width: 70
            }, {
                name: "remark",
                index: "remark",
                editable: false,
                width: 150
            }, {
                name: "fpHead",
                index: "fpHead",
                editable: false,
                width: 70
            }, {
                name: "formatCtime",
                index: "formatCtime",
                editable: false,
                width: 140
            }, {
                name: "operate",
                index: "operate",
                editable: false,
                // formatter:operateFmatter,
                width: 60
            }],
            pager: "#pager_data_list",
            jsonReader: {
                root: "data", "page": "page", total: "total",
                records: "records", repeatitems: false
            },
            viewrecords: true,
            hidegrid: false,
            gridComplete: function () {
                dataWrapper();
            }
        });
        jQuery("#data_list").jqGrid('navGrid', '#pager_data_list', {add: false, edit: false, del: false});
        $(window).bind("resize", function () {
            var width = $(".jqGrid_wrapper").width();
            $("#data_list").setGridWidth(width);
        });
    }

    function dataWrapper() {
        var ids = jQuery("#data_list").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var id = ids[i];
            var dataFromTheRow = jQuery('#data_list').jqGrid('getRowData', id);
            var html = "<a href='#' style='color:#f60' onclick='print1(" + id + ")' >打印</a>";
            jQuery("#data_list").jqGrid('setRowData', ids[i], {
                operate: html,
                realPay: toFixedForPrice(dataFromTheRow.realPay * 1)
            });

        }
    }

    // function operateFmatter(cellvalue, options, rowObject){
    // 	var html = "<a href='#' style='color:#f60' onclick='print1("+options.rowId+")' >打印</a>";
    // 	return html;
    // }

    function operateFmatterForDishes(cellvalue, options, rowObject) {

        var dishes = [];
        dishesDY = rowObject.orderDishes;
        for (var i = 0; i < rowObject.orderDishes.length; i++) {
            dishes.push("菜品：" + rowObject.orderDishes[i].name + " 数量：" + rowObject.orderDishes[i].mtime + " 单价：¥" + toFixedForPrice(rowObject.orderDishes[i].price));
        }
        return dishes.join(',');
    }

    function toFixedForPrice(price) {
        return (price * 1 / 100).toFixed(2);
    }

    //create menu
    $('#submitForSave').click(function () {
        $("#ajaxform").validate();
        if ($('#ajaxform').valid()) {
            var postData = $('#ajaxform').serializeArray();
            $.ajax(
                {
                    url: Config.createUrl,
                    type: "POST",
                    data: postData,
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        toastr.success(data.msg, data.title);
                        if (data && data.type == 'SUCCESS') {
                            location.reload();
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastr.error(errorThrown, textStatus);
                    }
                });
        }
        return false;
    });
    loadGrid();
    var flushFlag = 1;
    setInterval(function () {
    }, 5000);
    $("#btn_print").click(function () {
        $("div .jqGrid_wrapper").printMe();
    });

    $("#btn_flush").click(function () {
        document.location.reload();
    });
});

function print1(rowId) {
    var v = $('#data_list').jqGrid('getRowData', rowId);
    console.log(v);
    $("#print_orderNo").html("订单号：" + v.orderNo.substring(8, 12));
    $("#print_tableNo").html("餐座号： " + v.tableNo + "桌");
    $("#print_number").html("人数：" + v.cusNum);
    $("#dish_time").html("时间:" + v.formatCtime);
    $("#print_pay").html("合计：¥ " + v.realPay);
    $("#print_remark").html("备注：" + v.remark);
    $("#print_header").html("发票抬头：" + v.fpHead);
    var dishHtml = "<tr style=font-size:xx-small><td>菜品</td><td>数量</td><td>单价</td></tr><tr>";
    $.ajax({
        url: "/api/dinner/orders/id",
        type: "GET",
        data: {id: v.id},
        dataType: "json",
        async: false,
        success: function (data, textStatus, jqXHR) {
            console.log(data);
            for (var i = 0; i < data.data[0].orderDishes.length; i++) {
                dishHtml += "<tr style=font-size:xx-small><td>" + data.data[0].orderDishes[i].name + "</td><td>*" + data.data[0].orderDishes[i].mtime + "</td><td>" + toFixedForPrice(data.data[0].orderDishes[i].price) + "</td></tr><tr>"
            }
            $(".dish_table").find("tbody").html(dishHtml);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error(errorThrown, textStatus);
        }
    });

    $("#div_print").printMe();
}
function Delete(id) {
    updateDialog("DELETE", Config.deleteUrl + '/' + id);
    jQuery("#data_list").jqGrid('delRowData', id);
}

function updateDialog(action, url) {
    $.ajax(
        {
            url: url,
            type: action,
            success: function (data, textStatus, jqXHR) {
                if (action == 'DELETE') {
                    $("#data_list").trigger("reloadGrid");
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown);
            }
        });
}